package com.helen.ui.recoveryclass;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.coorchice.library.SuperTextView;
import com.helen.db.UserHelper;
import com.helen.entity.AddressListEntity;
import com.helen.entity.RecoveryClassEntity;
import com.helen.global.Constants;
import com.helen.shopping.R;
import com.helen.ui.BaseActivity;
import com.helen.ui.applymerchent.RecoveryAddressListActivity;
import com.helen.ui.recoveryorder.RecoveryOrderActivity;
import com.helen.utils.JsonUtil;
import com.helen.utils.KeybordUtils;
import com.helen.utils.MyLog;
import com.helen.utils.PhoneUtils;
import com.helen.utils.tiputils.MToast;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by yang on 2018/5/3.
 * 回收物品
 */

public class RecoveryCommonActivity extends BaseActivity {
    private static final int LOCATION = 0x11;
    private static final int CLASS = 0x12;

    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_detail_address)
    TextView tvDetailAddress;
    @BindView(R.id.ll_address)
    LinearLayout llAddress;
    @BindView(R.id.tv_class_name)
    TextView tvClassName;
    @BindView(R.id.ll_class)
    LinearLayout llClass;
    @BindView(R.id.tv_weight)
    TextView tvWeight;
    @BindView(R.id.et_weight)
    EditText etWeight;
    @BindView(R.id.ll_weight)
    LinearLayout llWeight;
    @BindView(R.id.view_weight_line)
    View viewWeightLine;
    @BindView(R.id.tv_color)
    TextView tvColor;
    @BindView(R.id.et_color)
    EditText etColor;
    @BindView(R.id.ll_color)
    LinearLayout llColor;
    @BindView(R.id.view_color_line)
    View viewColorLine;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.ll_time)
    LinearLayout llTime;
    @BindView(R.id.et_note)
    EditText etNote;
    @BindView(R.id.tv_note)
    TextView tvNote;
    @BindView(R.id.tv_sure)
    SuperTextView tvSure;
    private AddressListEntity addressListEntity;
    //    private RecoveryClassEntity recoveryClassEntity;
    private List<RecoveryClassEntity> selectedDataList = new ArrayList<>();
    private TimePickerView pvCustomTime;
    private String time = "";
    private int iid = 1;//分类参数
    private String url;
    private String strClassName;
    private String strClassIds;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_recovery_common;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        iid = getIntent().getIntExtra("iid", 1);
        String[] homeClassificationName = getResources().getStringArray(R.array.home_classification);
        notesApi();
        switch (iid) {
            case 1:
                getToolbarTitle().setText(homeClassificationName[0]);
                llColor.setVisibility(View.GONE);
                viewColorLine.setVisibility(View.GONE);
                url = Constants.API_JSONAPI_ADDCLOTHES;
                break;
            case 2:
                getToolbarTitle().setText(homeClassificationName[1]);
                llWeight.setVisibility(View.GONE);
                viewWeightLine.setVisibility(View.GONE);
                tvColor.setText("产品信息: ");
                etColor.setHint("请输入基本信息");
                url = Constants.API_JSONAPI_ADDELECTRONIC;
                break;
            case 3:
                getToolbarTitle().setText(homeClassificationName[2]);
                tvColor.setText("书籍成色: ");
                etColor.setHint("请输入书籍成色");
                url = Constants.API_JSONAPI_ADDBOOK;
                break;
            case 4:
                getToolbarTitle().setText(homeClassificationName[3]);
                llWeight.setVisibility(View.GONE);
                viewWeightLine.setVisibility(View.GONE);
                tvColor.setText("家具成色: ");
                etColor.setHint("请输入家具成色");
                url = Constants.API_JSONAPI_ADDFURNITURE;
                break;
            case 5:
                getToolbarTitle().setText(homeClassificationName[4]);
                tvWeight.setText("废品重量: ");
                etWeight.setHint("请输入废品重量(kg)");
                llColor.setVisibility(View.GONE);
                viewColorLine.setVisibility(View.GONE);
                url = Constants.API_JSONAPI_ADDWASTE;
                break;
        }

    }

    @Override
    protected void updateViews() {

    }


    @OnClick({R.id.ll_address, R.id.ll_class, R.id.ll_time, R.id.tv_sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_address:
                Intent ti = new Intent(this, RecoveryAddressListActivity.class);
                ti.putExtra("backModel", true);
                startActivityForResult(ti, LOCATION);
                break;
            case R.id.ll_class:
                if (iid == 2) {
                    Intent ti2 = new Intent(this, ElectronicClassActivity.class);
                    startActivityForResult(ti2, CLASS);
                } else {
                    Intent ti2 = new Intent(this, RecoveryClassActivity.class);
//                    ti2.putExtra("recoveryClassEntity", recoveryClassEntity);
                    ti2.putExtra("selectedDataList", (Serializable) selectedDataList);
                    ti2.putExtra("iid", iid);
                    startActivityForResult(ti2, CLASS);
                }

                break;
            case R.id.ll_time:
                if (KeybordUtils.isSoftShowing(RecoveryCommonActivity.this)) {
                    KeybordUtils.closeKeybord(etNote, RecoveryCommonActivity.this);
                }
                initCustomTimePicker();
                pvCustomTime.show();
                break;
            case R.id.tv_sure:
                if (addressListEntity == null) {
                    MToast.makeTextShort(RecoveryCommonActivity.this, "请选择地址").show();
                    return;
                }

//                if (recoveryClassEntity == null) {
//                    MToast.makeTextShort(RecoveryCommonActivity.this, "请选择分类").show();
//                    return;
//                }
                if (selectedDataList == null || selectedDataList.size() == 0) {
                    MToast.makeTextShort(RecoveryCommonActivity.this, "请选择分类").show();
                    return;
                }

                String weight = etWeight.getText().toString().trim();
                if (iid != 4 && iid != 2) {
                    if (TextUtils.isEmpty(weight)) {
                        MToast.makeTextShort(RecoveryCommonActivity.this, "请输入重量").show();
                        return;
                    }
                }


                if (TextUtils.isEmpty(time)) {
                    MToast.makeTextShort(RecoveryCommonActivity.this, "请选择预约上门时间").show();
                    return;
                }

                String remarks = etNote.getText().toString().trim();


                switch (iid) {
                    case 1:
                    case 5:
//                        sureRecoveryApi(recoveryClassEntity.getId() + "", addressListEntity.getId() + "", weight, remarks, "");
                        sureRecoveryApi(strClassIds, addressListEntity.getId() + "", weight, remarks, "");
                        break;
                    case 3:
                        String quality = etColor.getText().toString().trim();
                        if (TextUtils.isEmpty(quality)) {
                            MToast.makeTextShort(RecoveryCommonActivity.this, "请输入书籍成色").show();
                            return;
                        }
//                        sureRecoveryApi(recoveryClassEntity.getId() + "", addressListEntity.getId() + "", weight, remarks, quality);
                        sureRecoveryApi(strClassIds, addressListEntity.getId() + "", weight, remarks, quality);
                        break;
                    case 4:
                        String quality2 = etColor.getText().toString().trim();
                        if (TextUtils.isEmpty(quality2)) {
                            MToast.makeTextShort(RecoveryCommonActivity.this, "请输入家具成色").show();
                            return;
                        }
//                        sureRecoveryApi(recoveryClassEntity.getId() + "", addressListEntity.getId() + "", "", remarks, quality2);
                        sureRecoveryApi(strClassIds, addressListEntity.getId() + "", "", remarks, quality2);
                        break;

                    case 2:
                        String info = etColor.getText().toString().trim();
                        if (TextUtils.isEmpty(info)) {
                            MToast.makeTextShort(RecoveryCommonActivity.this, "请输入基本信息").show();
                            return;
                        }
//                        sureRecoveryApi(recoveryClassEntity.getId() + "", addressListEntity.getId() + "", "", remarks, info);
                        sureRecoveryApi(strClassIds, addressListEntity.getId() + "", "", remarks, info);
                        break;
                }


                break;
        }
    }

//    回收旧衣服
//    用户名	userid
//    分类编号	classid
//    地址编号	addressid
//    重量（kg）	weight
//    上门取货时间	time
//    备注	remarks


//回收电子产品
//    用户名	userid
//    分类编号	classid
//    地址编号	addressid
//    电子产品基本信息描述	content
//    上门取货时间	time
//    备注	remarks


//    回收垃圾
//    用户名	userid
//    分类编号	classid
//    地址编号	addressid
//    重量（kg）	weight
//    上门取货时间	time
//    备注	remarks

//    回收书籍
//    用户名	userid
//    分类编号	classid
//    地址编号	addressid
//    重量（kg）	weight
//    书籍成色	quality
//    上门取货时间	time
//    备注	remarks

//    回收家具
//    用户名	userid
//    分类编号	classid
//    地址编号	addressid
//    家具成色	quality
//    上门取货时间	time
//    备注	remarks


    private void sureRecoveryApi(String classid, String cityId, String weight, String remarks, String quality) {
        mMProgressDialog.show();
        HttpParams params = new HttpParams();
        params.put("userid", UserHelper.getInstance().getloginEntity(RecoveryCommonActivity.this).getId());
        params.put("classid", classid);
        params.put("cityId", cityId);

//        回收家具不需要重量参数，其它都需要
        if (iid != 4 && iid != 2) {
            params.put("weight", weight + "");
        }
        params.put("time", time);
        params.put("remarks", remarks);

        switch (iid) {
            case 2:
                params.put("content", quality);
                break;
            // 回收书籍和家具需要颜色
            case 3:
            case 4:
                params.put("quality", quality);
                break;
        }

        EasyHttp.post(url)
                .params(params)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onError(ApiException e) {
                        MyLog.d(TAG, "回收失败==" + e.toString());
                        MToast.makeTextShort(RecoveryCommonActivity.this, getString(R.string.service_error)).show();
                    }

                    @Override
                    public void onSuccess(String result) {
                        String data = PhoneUtils.checkResponseFlag(RecoveryCommonActivity.this, result, TAG);
                        if (data != null) {
                            Intent ti = new Intent(RecoveryCommonActivity.this, RecoveryOrderActivity.class);
                            startActivity(ti);
                            MToast.makeTextShort(RecoveryCommonActivity.this, "提交成功").show();
                            finish();
                        }

                    }
                });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case LOCATION:
                    if (data != null) {
                        addressListEntity = (AddressListEntity) data.getSerializableExtra("addressListEntity");
                        tvName.setText("姓名: " + addressListEntity.getName());
                        tvPhone.setText(addressListEntity.getPhone());
                        tvDetailAddress.setText("详细地址: " + addressListEntity.getCityName() + addressListEntity.getDetail());
                    }
                    break;
                case CLASS:
                    if (data != null) {
//                        recoveryClassEntity = (RecoveryClassEntity) data.getSerializableExtra("recoveryClassEntity");
//                        tvClassName.setText(recoveryClassEntity.getName());
                        selectedDataList = (List<RecoveryClassEntity>) data.getSerializableExtra("selectedDataList");
                        strClassIds = "";
                        strClassName = "";
                        for (int i = 0; i < selectedDataList.size(); i++) {
                            strClassIds += (TextUtils.isEmpty(strClassIds) ? "" : ",") + selectedDataList.get(i).getId() + "";
                            strClassName += (TextUtils.isEmpty(strClassName) ? "" : ",") + selectedDataList.get(i).getName();
                        }
                        tvClassName.setText(strClassName);
                    }

                    break;
            }
        }
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            if (mTimePickerView.isShowing()) {
//                mTimePickerView.dismiss();
//                return true;
//            }
//        }
//        return super.onKeyDown(keyCode, event);
//    }

    private void initCustomTimePicker() {

        /**
         * @description
         *
         * 注意事项：
         * 1.自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针.
         * 具体可参考demo 里面的两个自定义layout布局。
         * 2.因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
         * setRangDate方法控制起始终止时间(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
         */
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(2018, 0, 31);
        Calendar endDate = Calendar.getInstance();
        endDate.set(2027, 11, 31);
        //时间选择器 ，自定义布局
        pvCustomTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                // yyyy-MM-dd HH:mm
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
                time = format.format(date);
                MyLog.e("yang", "time==" + time);
                tvTime.setText(format.format(date));

            }
        })

                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setLayoutRes(R.layout.pickerview_custom_time, new CustomListener() {

                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        TextView tvCancel = (TextView) v.findViewById(R.id.tv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomTime.returnData();
                                pvCustomTime.dismiss();
                            }
                        });
                        tvCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomTime.dismiss();
                            }
                        });
                    }
                })
                .setContentTextSize(18)
                .setType(new boolean[]{true, true, true, true, false, false})
                .setLabel("年", "月", "日", "时", "分", "秒")
                .setLineSpacingMultiplier(1.2f)
                .setTextXOffset(0, 0, 0, 40, 0, -40)
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(0xFFFF7A00)
                .build();

    }


    //    用户须知api API_JSONAPI_NOTES
    private void notesApi() {
        HttpParams params = new HttpParams();
        params.put("iid", iid + "");
        MyLog.e("yang","iid===================="+iid);
        EasyHttp.post(Constants.API_JSONAPI_NOTES)
                .params(params)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(ApiException e) {
                        MToast.makeTextShort(RecoveryCommonActivity.this, getString(R.string.service_error)).show();
                    }

                    @Override
                    public void onSuccess(String result) {
                        MyLog.e("yang", "用户须知==" + result);
                        int code = JsonUtil.getJsonValuesInt(result, "code");
                        String msg = JsonUtil.getJsonValuesString(result, "msg");
                        if (code == 0) {
                            String content = JsonUtil.getJsonValuesString(result, "content").replace("\\n","\n");
                            tvNote.setText(content);
                        }else {
                            MToast.makeTextShort(RecoveryCommonActivity.this, msg).show();
                        }

                    }
                });


    }
}
